package com.spark.incoicings.config;

import com.spark.incoicings.service.ProductService;
import com.spark.invoicings.entity.Product;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.util.List;

@Configuration
public class ApplicationStartListener implements ApplicationListener<ContextRefreshedEvent> {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private ProductService productService;

    /**
     *  Spring Framework 的事件监听器方法
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        List<Product> products = productService.list();
        if (products!=null){
            for (Product product : products){
                Integer currentInventory = product.getCurrentInventory();
                redisTemplate.opsForValue().set("product_stack"+":"+product.getProductId(),currentInventory);
            }
        }
    }
}
